import uuid
import os
import random
import time
import re
import datetime
import requests
from flask import Flask, request, jsonify, current_app, send_from_directory
from flask_cors import CORS
from flask_jwt_extended import JWTManager, create_access_token, get_jwt_identity, jwt_required, decode_token
import pymysql
from pymysql.cursors import DictCursor
import bcrypt
from dbutils.pooled_db import PooledDB
from flask_mail import Mail, Message
import json
from datetime import timedelta

from X1_http import get_answer

# 加载环境变量
if os.environ.get('FLASK_ENV') == 'development':
    from dotenv import load_dotenv

    load_dotenv()

# 应用初始化
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})  # 允许所有域名访问 /api 开头的接口

# JWT配置
app.config['JWT_SECRET_KEY'] = os.environ.get('JWT_SECRET_KEY', uuid.uuid4().hex)  # 生产环境需修改
jwt_secret = os.environ.get('JWT_SECRET_KEY')
if not jwt_secret:
    if os.environ.get('FLASK_ENV') == 'production':
        raise RuntimeError('JWT_SECRET_KEY 环境变量未设置！')
    # 仅开发环境使用固定默认值
    app.config['JWT_SECRET_KEY'] = 'your-dev-secret-key-here'
else:
    app.config['JWT_SECRET_KEY'] = jwt_secret
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=24)  # 明确token有效期

jwt = JWTManager(app)

# 文件上传配置
UPLOAD_FOLDER = os.path.join(os.getcwd(), 'uploads')
AVATAR_FOLDER = os.path.join(UPLOAD_FOLDER, 'avatars')
os.makedirs(AVATAR_FOLDER, exist_ok=True)  # 确保目录存在

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB 上传限制

# 数据库连接池配置
pool = PooledDB(
    creator=pymysql,
    host=os.environ.get('DB_HOST', '47.113.150.140'),
    user=os.environ.get('DB_USER', 'root'),
    port=int(os.environ.get('DB_PORT', 8081)),
    password=os.environ.get('DB_PASSWORD', 'root'),
    database=os.environ.get('DB_NAME', 'lyex'),
    charset="utf8mb4",
    maxconnections=20,
    maxcached=5,
    mincached=2,
    blocking=True,  # 确保连接耗尽时会等待
    cursorclass=DictCursor)

# 配置邮件服务器（163邮箱示例）
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = '2285213226@qq.com'  # 替换为你的邮箱
app.config['MAIL_PASSWORD'] = 'vttsllyenrebecde'  # 替换为邮箱授权码
app.config['MAIL_DEFAULT_SENDER'] = ('暑假大模型项目', '2285213226@qq.com')
mail = Mail(app)

# 星火大模型配置
SPARK_API_KEY = "Bearer WAFmivwUnPFfnSDdUHyi:BsSnFeAafCFMVzIbJjqR"  # 替换为实际密钥
SPARK_API_URL = "https://spark-api-open.xf-yun.com/v1/chat/completions"


# 获取数据库连接
def get_db_connection():
    try:
        return pool.connection()
    except Exception as e:
        print(f"数据库连接错误: {e}")
        raise


# 静态文件服务（用于访问上传的头像）
@app.route('/uploads/<path:filename>')
def serve_uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)


# 发送邮箱验证码（存入t_email）
@app.route('/api/auth/send-code', methods=['POST'])
def send_verify_code():
    data = request.get_json()
    email = data.get('email')

    if not email:
        return jsonify({'error': '请输入邮箱'}), 400

    # 验证邮箱格式
    email_regex = r'^[^\s@]+@[^\s@]+\.[^\s@]+$'
    if not re.match(email_regex, email):
        return jsonify({'error': '邮箱格式不正确'}), 400

    try:
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                # 检查邮箱是否已注册
                cursor.execute("SELECT * FROM t_user WHERE email = %s", (email,))
                if cursor.fetchone():
                    return jsonify({'error': '邮箱已注册'}), 400

                # 生成6位随机验证码
                code = ''.join(random.sample('0123456789', 6))

                # 检查5分钟内是否已有验证码（复用逻辑）
                cursor.execute(
                    "SELECT code FROM t_email WHERE email = %s AND createTime >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)",
                    (email,)
                )
                res = cursor.fetchone()

                if res:
                    code = res['code']  # 复用已有验证码
                    print(f"复用验证码: {code} -> {email}")
                else:
                    # 插入新验证码到t_email（含时间戳，便于过期校验）
                    cursor.execute(
                        "INSERT INTO t_email (email, code, createTime) VALUES (%s, %s, NOW())",
                        (email, code)
                    )
                    conn.commit()
                    print(f"新验证码: {code} -> {email}")

        # 发送邮件
        msg = Message(
            subject="大模型项目注册验证码",
            recipients=[email],
            body=f"你的注册验证码是：{code}，5分钟内有效，请勿泄露给他人。"
        )
        try:
            mail.send(msg)
            print(f"邮件发送成功：{email}")
        except Exception as mail_err:
            print(f"邮件发送失败：{str(mail_err)}")
            # 发送失败时回滚t_email记录
            with get_db_connection() as conn:
                with conn.cursor() as cursor:
                    cursor.execute("DELETE FROM t_email WHERE email = %s AND code = %s", (email, code))
                    conn.commit()
            return jsonify({'error': '邮件发送失败，请检查邮箱是否正确'}), 500

        return jsonify({
            'success': True,
            'message': '验证码已发送至邮箱'
        })

    except Exception as e:
        print(f"发送验证码异常: {str(e)}")
        return jsonify({'error': '系统错误，请稍后重试'}), 500


# 账号密码登录（仅POST方法）
@app.route('/api/auth/login/account', methods=['POST'])
def login_account():
    data = request.get_json()
    identifier = data.get('identifier')  # 用户名或邮箱
    password = data.get('password')

    if not identifier or not password:
        return jsonify({'error': '请输入账号和密码'}), 400

    try:
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                # 明确查询需要的字段（避免SELECT *的安全隐患）
                cursor.execute("""
                    SELECT id, name, email, pwd, role, avatar 
                    FROM t_user 
                    WHERE name = %s OR email = %s
                """, (identifier, identifier))
                user = cursor.fetchone()

        if not user:
            return jsonify({'error': '账号不存在'}), 401

        # 验证密码（bcrypt哈希校验）
        stored_pwd = user['pwd'].encode('utf-8')
        if not bcrypt.checkpw(password.encode('utf-8'), stored_pwd):
            return jsonify({'error': '密码错误'}), 401

        # 生成JWT令牌（包含用户ID）
        access_token = create_access_token(identity=str(user['id']))

        # 存储逻辑：
        # 1. 删除用户旧token（确保每个用户只有一个有效token）
        # 2. 插入新token（包含创建时间和过期时间）
        # 存储token到数据库（补全字段，修复创建时间缺失问题）
        try:
            # 解析JWT获取过期时间（使用UTC时间避免时区问题）
            # 不传递 secret 参数，decode_token 会自动从应用配置中获取
            payload = decode_token(
                encoded_token=access_token,
                csrf_value=None,  # 如果不需要 CSRF 保护，可以为 None
                allow_expired=False  # 是否允许过期 token
            )
            exp_timestamp = payload['exp']
            expires_at = datetime.datetime.fromtimestamp(exp_timestamp, tz=datetime.timezone.utc)
            created_at = datetime.datetime.now(datetime.timezone.utc)  # 记录创建时间（UTC）

            with get_db_connection() as conn:
                with conn.cursor() as cursor:
                    # 插入新token（包含created_at字段）
                    cursor.execute("""
                        INSERT INTO t_user_token 
                        (user_id, token, created_at, expires_at) 
                        VALUES (%s, %s, %s, %s)
                    """, (user['id'], access_token, created_at, expires_at))
                    conn.commit()
        except Exception as e:
            app.logger.error(f"存储token失败: {str(e)}")  # 日志记录错误
            # 不阻断登录流程

        # 更新最后登录时间
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("UPDATE t_user SET last_login = NOW() WHERE id = %s", (user['id'],))
                conn.commit()

        return jsonify({
            'success': True,
            'message': '登录成功',
            'token': access_token,  # JWT 令牌
            'user': {
                'id': user['id'],
                'name': user['name'],
                'email': user['email'],
                'role': user.get('role', 'user'),
                'avatar': user.get('avatar', '')
            }
        })

    except Exception as e:
        app.logger.error(f"登录异常: {str(e)}")
        return jsonify({'error': '登录失败，请稍后重试'}), 500


# 注册接口（将账号密码存入t_user）
@app.route('/api/auth/register', methods=['POST'])
def register():
    data = request.get_json()
    email = data.get('email')
    code = data.get('verifyCode')
    password = data.get('pwd')
    username = data.get('name')  # 允许自定义用户名（若无则用邮箱前缀）
    print(f"注册请求: {email}, {username}")  # 添加日志
    # 基础参数校验
    if not all([email, code, password]):
        return jsonify({'error': '请完善邮箱、验证码和密码'}), 400

    # 密码强度校验（至少6位）
    if len(password) < 6:
        return jsonify({'error': '密码长度至少6位'}), 400

    try:
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                # 1. 验证验证码（从t_email查询，确保5分钟内有效）
                cursor.execute(
                    "SELECT * FROM t_email WHERE email = %s AND code = %s AND createTime >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)",
                    (email, code)
                )
                valid_code = cursor.fetchone()
                print(f"验证码查询结果：{valid_code}")  # 新增日志
                if not valid_code:
                    return jsonify({'error': '验证码错误或已过期'}), 400

                # 2. 检查邮箱是否已注册
                cursor.execute("SELECT * FROM t_user WHERE email = %s", (email,))
                if cursor.fetchone():
                    return jsonify({'error': '邮箱已注册'}), 400

                # 3. 处理用户名（默认用邮箱前缀）
                if not username:
                    username = email.split('@')[0]
                    # 若用户名重复，添加随机后缀
                    cursor.execute("SELECT * FROM t_user WHERE name = %s", (username,))
                    if cursor.fetchone():
                        username += str(random.randint(100, 999))

                # 4. 密码加密（bcrypt哈希）
                hashed_pwd = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
                print(f"生成哈希密码: {hashed_pwd[:20]}...")  # 添加日志
                # 5. 插入 用户到t_user表
                cursor.execute(
                    "INSERT INTO t_user (name, email, pwd, role, created_at, avatar) VALUES (%s, %s, %s, 'user', NOW(), 'default_avatar.png')",
                    (username, email, hashed_pwd)
                )
                print(f"执行插入语句: {username}, {email}")  # 添加日志
                # 6. 注册成功后删除已使用的验证码（避免重复注册）
                cursor.execute("DELETE FROM t_email WHERE id = %s", (valid_code['id'],))
                conn.commit()
                print("事务提交成功")  # 添加日志

        return jsonify({
            'success': True,
            'message': '注册成功，请登录',
            'username': username
        })

    except Exception as e:
        print(f"注册异常: {str(e)}")
        return jsonify({'error': '注册失败，请稍后重试'}), 500


@app.route('/api/auth/forgot-password/send-code', methods=['POST'])
def send_forgot_password_code():
    data = request.get_json()
    email = data.get('email')

    if not email:
        return jsonify({'error': '请输入邮箱'}), 400

    try:
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                # 检查邮箱是否存在
                cursor.execute("SELECT * FROM t_user WHERE email = %s", (email,))
                user = cursor.fetchone()
                if not user:
                    return jsonify({'error': '邮箱不存在'}), 404

                # 生成验证码
                code = ''.join(random.sample('0123456789', 6))

                # 检查5分钟内是否已有验证码
                cursor.execute(
                    "SELECT code FROM t_email WHERE email = %s AND createTime >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)",
                    (email,)
                )
                existing_code = cursor.fetchone()

                if existing_code:
                    code = existing_code['code']
                else:
                    cursor.execute(
                        "INSERT INTO t_email (email, code, createTime) VALUES (%s, %s, NOW())",
                        (email, code)
                    )
                    conn.commit()

        # 发送邮件
        msg = Message(
            subject="密码重置验证码",
            recipients=[email],
            body=f"您的验证码是：{code}，5分钟内有效"
        )
        mail.send(msg)

        return jsonify({'message': '验证码已发送'}), 200

    except Exception as e:
        print(f"发送验证码异常: {str(e)}")
        return jsonify({'error': '系统错误'}), 500


@app.route('/api/auth/reset-password', methods=['POST'])
def reset_password():
    data = request.get_json()
    email = data.get('email')
    verify_code = data.get('verifyCode')
    new_password = data.get('newPassword')

    if not all([email, verify_code, new_password]):
        return jsonify({'error': '请填写所有字段'}), 400

    try:
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                # 验证验证码
                cursor.execute(
                    "SELECT * FROM t_email WHERE email = %s AND code = %s AND createTime >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)",
                    (email, verify_code)
                )
                valid_code = cursor.fetchone()
                if not valid_code:
                    return jsonify({'error': '验证码错误或已过期'}), 400

                # 检查邮箱是否存在
                cursor.execute("SELECT * FROM t_user WHERE email = %s", (email,))
                user = cursor.fetchone()
                if not user:
                    return jsonify({'error': '邮箱不存在'}), 404

                # 更新密码
                hashed_pwd = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
                cursor.execute(
                    "UPDATE t_user SET pwd = %s WHERE email = %s",
                    (hashed_pwd, email)
                )
                conn.commit()

                # 删除已使用的验证码
                cursor.execute("DELETE FROM t_email WHERE id = %s", (valid_code['id'],))
                conn.commit()

        return jsonify({'message': '密码重置成功'}), 200

    except Exception as e:
        print(f"重置密码异常: {str(e)}")
        return jsonify({'error': '系统错误'}), 500


# 获取当前用户信息
@app.route('/api/user/info', methods=['GET'])
@jwt_required()
def get_user_info():
    current_user = get_jwt_identity()

    try:
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                # 查询用户信息
                cursor.execute("""
                    SELECT 
                        id, 
                        name as nickname, 
                        email, 
                        avatar, 
                        created_at as register_time, 
                        last_login 
                    FROM t_user 
                    WHERE id = %s
                """, (current_user,))

                user = cursor.fetchone()

                if not user:
                    return jsonify({"error": "User not found"}), 404

                # 格式化日期时间
                if user['register_time']:
                    user['register_time'] = user['register_time'].strftime('%Y-%m-%d %H:%M:%S')

                if user['last_login']:
                    user['last_login'] = user['last_login'].strftime('%Y-%m-%d %H:%M:%S')

                return jsonify({
                    "success": True,
                    "user": user
                }), 200

    except Exception as e:
        app.logger.error(f"Error fetching user info: {str(e)}")
        return jsonify({"error": "Failed to fetch user information"}), 500


# 用户信息更新接口
@app.route('/api/user/update', methods=['POST'])
@jwt_required()
def update_user_info():
    current_user = get_jwt_identity()
    data = request.get_json()

    if not data:
        return jsonify({"error": "No data provided"}), 400

    try:
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                # 查询当前用户
                cursor.execute("SELECT * FROM t_user WHERE id = %s", (current_user,))
                user = cursor.fetchone()

                if not user:
                    return jsonify({"error": "User not found"}), 404

                # 更新用户信息
                update_fields = {}
                if 'nickname' in data and data['nickname'] != user.get('name'):
                    update_fields['name'] = data['nickname']

                if 'email' in data and data['email'] != user.get('email'):
                    # 验证邮箱格式
                    email_regex = r'^[^\s@]+@[^\s@]+\.[^\s@]+$'
                    if not re.match(email_regex, data['email']):
                        return jsonify({"error": "Invalid email format"}), 400

                    # 检查邮箱是否已被使用
                    cursor.execute("SELECT id FROM t_user WHERE email = %s AND id != %s",
                                   (data['email'], current_user))
                    if cursor.fetchone():
                        return jsonify({"error": "Email already exists"}), 400

                    update_fields['email'] = data['email']

                if 'avatar' in data:
                    # 保存头像URL
                    update_fields['avatar'] = data['avatar']

                # 如果有更新字段，执行更新
                if update_fields:
                    set_clause = ", ".join([f"{k} = %s" for k in update_fields.keys()])
                    values = list(update_fields.values()) + [current_user]

                    cursor.execute(f"UPDATE t_user SET {set_clause} WHERE id = %s", values)
                    conn.commit()

                # 更新最后登录时间
                cursor.execute("UPDATE t_user SET last_login = NOW() WHERE id = %s", (current_user,))
                conn.commit()

                # 返回更新后的用户信息
                cursor.execute(
                    "SELECT id, name as nickname, email, avatar, created_at as register_time, last_login FROM t_user WHERE id = %s",
                    (current_user,))
                updated_user = cursor.fetchone()

                # 格式化日期时间
                if updated_user['register_time']:
                    updated_user['register_time'] = updated_user['register_time'].strftime('%Y-%m-%d %H:%M:%S')

                if updated_user['last_login']:
                    updated_user['last_login'] = updated_user['last_login'].strftime('%Y-%m-%d %H:%M:%S')

                return jsonify({
                    "message": "User information updated successfully",
                    "user": updated_user
                }), 200

    except Exception as e:
        app.logger.error(f"Error updating user info: {str(e)}")
        return jsonify({"error": "Failed to update user information"}), 500


# 头像上传接口
@app.route('/api/user/avatar', methods=['POST'])
@jwt_required()
def upload_avatar():
    current_user = get_jwt_identity()

    # 检查是否有文件上传
    if 'avatar' not in request.files:
        return jsonify({"error": "No avatar file provided"}), 400

    file = request.files['avatar']

    # 验证文件类型和大小
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    # 允许的文件类型
    allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'}

    def allowed_file(filename):
        return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions

    if not allowed_file(file.filename):
        return jsonify({"error": "Invalid file type. Allowed types: png, jpg, jpeg, gif"}), 400

    # 限制文件大小（1MB）
    if len(file.read()) > 1 * 1024 * 1024:
        return jsonify({"error": "File size exceeds 1MB"}), 400
    file.seek(0)  # 重置文件指针

    try:
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                # 查询用户
                cursor.execute("SELECT id FROM t_user WHERE id = %s", (current_user,))
                user = cursor.fetchone()

                if not user:
                    return jsonify({"error": "User not found"}), 404

                # 创建用户头像目录（如果不存在）
                user_dir = os.path.join(app.config['UPLOAD_FOLDER'], 'avatars', str(current_user))
                os.makedirs(user_dir, exist_ok=True)

                # 生成唯一文件名
                file_ext = os.path.splitext(file.filename)[1].lower()
                filename = f"{uuid.uuid4().hex}{file_ext}"
                file_path = os.path.join(user_dir, filename)

                # 保存文件
                file.save(file_path)

                # 构建可访问的URL
                avatar_url = f"/uploads/avatars/{current_user}/{filename}"

                # 更新用户头像URL
                cursor.execute("UPDATE t_user SET avatar = %s WHERE id = %s", (avatar_url, current_user))
                conn.commit()

                return jsonify({
                    "message": "Avatar uploaded successfully",
                    "avatar_url": avatar_url
                }), 200

    except Exception as e:
        app.logger.error(f"Error uploading avatar: {str(e)}")
        return jsonify({"error": "Failed to upload avatar"}), 500


# 管理员获取所有用户（需管理员权限）
@app.route('/api/admin/users', methods=['GET'])
@jwt_required()
def get_all_users():
    user_id = get_jwt_identity()
    try:
        # 验证当前用户是否为管理员
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute('SELECT role FROM t_user WHERE id = %s', (user_id,))
                user = cursor.fetchone()
                if not user or user['role'] != 'admin':
                    return jsonify({'error': '无管理员权限'}), 403

                # 查询所有用户（排除密码）
                cursor.execute('SELECT id, name, email, role, created_at, avatar, last_login FROM t_user')
                users = cursor.fetchall()

        # 格式化日期时间
        for user in users:
            if user['created_at']:
                user['created_at'] = user['created_at'].strftime('%Y-%m-%d %H:%M:%S')
            if user['last_login']:
                user['last_login'] = user['last_login'].strftime('%Y-%m-%d %H:%M:%S')

        return jsonify({
            'success': True,
            'users': users
        })

    except Exception as e:
        print(f"获取用户列表异常: {str(e)}")
        return jsonify({'error': '获取用户列表失败'}), 500


# 数据库连接测试接口
@app.route('/test/db')
def test_db():
    try:
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT 1")
                result = cursor.fetchone()
                return jsonify({'success': True, 'result': result})
    except Exception as e:
        return jsonify({'error': f'数据库连接失败: {str(e)}'}), 500


# 调用星火大模型（核心逻辑）
def call_spark_model(messages):
    headers = {
        "Authorization": SPARK_API_KEY,
        "Content-Type": "application/json"
    }
    payload = {
        "model": "4.0Ultra",  # 确认模型名称是否正确
        "user": "user_id",
        "messages": messages,
        "stream": False,
        "tools": [
            {
                "type": "web_search",
                "web_search": {
                    "enable": True,
                    "search_mode": "deep"
                }
            }
        ]
    }
    app.logger.info(f"调用星火API: {payload}")
    try:
        response = requests.post(
            SPARK_API_URL,
            json=payload,
            headers=headers,
            timeout=30
        )
        response.raise_for_status()
        result = response.json()
        return result["choices"][0]["message"]["content"]
    except requests.exceptions.RequestException as e:
        app.logger.error(f"星火API请求失败: {str(e)}")
        raise
    except KeyError as e:
        app.logger.error(f"响应解析失败（缺少字段）: {str(e)}")
        raise
    except Exception as e:
        app.logger.error(f"调用星火模型异常: {str(e)}")
        raise


# 大模型会话接口
@app.route('/api/chat', methods=['POST'])
@jwt_required()
def chat_with_model():
    app.logger.info("接收到会话请求")
    data = request.get_json()
    session_id = data.get('id')  # 会话ID（新会话为None）
    content = data.get('content')  # 用户输入

    if not content:
        return jsonify({'error': '请输入对话内容'}), 400

    user_id = get_jwt_identity()  # 从JWT获取用户ID

    try:
        with get_db_connection() as conn:
            with conn.cursor() as cursor:
                # 1. 处理会话（创建或验证权限）
                if session_id:
                    # 验证会话归属
                    cursor.execute("""
                        SELECT * FROM t_chat_session 
                        WHERE id = %s AND user_id = %s
                    """, (session_id, user_id))
                    session = cursor.fetchone()
                    if not session:
                        return jsonify({'error': '会话不存在或无权限访问'}), 403
                else:
                    # 创建新会话（优化标题显示）
                    title = content[:20] + ('...' if len(content) > 20 else '')
                    cursor.execute("""
                        INSERT INTO t_chat_session (user_id, title) 
                        VALUES (%s, %s)
                    """, (user_id, title))
                    session_id = cursor.lastrowid
                    conn.commit()

                # 2. 查询会话历史消息（构造上下文）
                cursor.execute("""
                    SELECT userType, content FROM t_chat 
                    WHERE conversationId = %s 
                    ORDER BY id ASC
                """, (session_id,))
                history = cursor.fetchall()
                messages = []
                for item in history:
                    # 转换角色格式（user -> user，model -> assistant）
                    role = "user" if item["userType"] == "user" else "assistant"
                    messages.append({"role": role, "content": item["content"]})

                # 3. 添加当前用户输入到上下文
                messages.append({"role": "user", "content": content})

                # 保存用户消息
                cursor.execute("""
                    INSERT INTO t_chat (userType, content, conversationId) 
                    VALUES (%s, %s, %s)
                """, ('user', content, session_id))
                conn.commit()

                # 4. 调用星火大模型
                # model_response = call_spark_model(messages)
                model_response = get_answer(messages)

                # 保存模型回复
                cursor.execute("""
                    INSERT INTO t_chat (userType, content, conversationId) 
                    VALUES (%s, %s, %s)
                """, ('model', model_response, session_id))
                conn.commit()

        return jsonify({
            'id': session_id,
            'content': model_response
        })

    except requests.exceptions.Timeout:
        app.logger.error("大模型请求超时")
        return jsonify({'error': '请求超时，请重试'}), 504
    except requests.exceptions.HTTPError as e:
        app.logger.error(f"大模型API错误: {str(e)}")
        return jsonify({'error': '服务暂不可用，请稍后再试'}), 503
    except Exception as e:
        app.logger.error(f"大模型交互异常: {str(e)}")
        return jsonify({'error': '系统错误，请稍后重试'}), 500


if __name__ == '__main__':
    # 打印路由信息
    print("注册的路由列表：")
    for rule in app.url_map.iter_rules():
        print(f"路径: {rule.rule}, 方法: {rule.methods}, 端点: {rule.endpoint}")
    app.run(host='0.0.0.0', port=5000, debug=True)  # 生产环境关闭debug